package com.cjbdi.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjbdi.entity.Fypz;
import com.cjbdi.entity.UserInfo;
import com.cjbdi.entity.UserSubscribe;
import com.cjbdi.pagination.PageInfo;
import com.cjbdi.service.TFypzService;
import com.cjbdi.service.UserService;
import com.cjbdi.service.UserSubscribeService;
import com.cjbdi.tree.FyNodeView;
import com.cjbdi.tree.FyTreeBuildUtil;
import com.cjbdi.tree.FyTreeItem;
import com.cjbdi.util.IpUtil;
import com.cjbdi.util.NumUtil;
import com.cjbdi.util.PropertiesUtil;
import com.cjbdi.util.StringEditor;
import com.cjbdi.vo.JsonResult;
import com.cjbdi.vo.Result;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserSubscribeService subscribeService;
    @Autowired 
    TFypzService tFypzService; 
    @RequestMapping(value = "/save", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result save(UserInfo userInfo) {
    	List<UserInfo> list = userService.findByIp(userInfo.getUserip());
    	if(list.size()>0) {
    		return new Result(401,"用户IP已经存在",null);
    	}else {
    		String fybm = userInfo.getFybm();
    		fybm = new StringEditor(fybm).trimAll().toString();
        	if(fybm.substring(1).equals("00")) {
        		userInfo.setFytype("高");
        	}else if(fybm.substring(2).equals("0")) {
        		userInfo.setFytype("中");
        	}else {
        		userInfo.setFytype("辖");
        	}
        	String province = PropertiesUtil.getProperty(fybm.substring(0, 1));
        	userInfo.setProvince(province);
        	userService.save(userInfo);
        	UserSubscribe userSubscribe = new UserSubscribe();
        	userSubscribe.setFybm(fybm);
        	userSubscribe.setName(userInfo.getName());
        	userSubscribe.setFymc(userInfo.getFymc());
        	userSubscribe.setIp(userInfo.getUserip());
        	userSubscribe.setSfunction(userInfo.getSubscribes());
        	userSubscribe.setCreated(NumUtil.GetNowDate("yyyy-MM-dd HH:mm:ss"));
        	userSubscribe.setStatus("开通");
        	subscribeService.save(userSubscribe);
        	return new Result(200,"新增用户成功",null);

    	}
    	
    }
    @RequestMapping(value = "/edit", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result edit(int id) {
    	List<UserInfo> list = userService.findById(id);
    	if(list.size()>0) {
    		return new Result(200,"获取用户信息成功",list.get(0));
    	}else {
        	return new Result(402,"获取用户信息失败",null);

    	}
    	
    }
    @RequestMapping(value = "/update", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
	public Result update(UserInfo userInfo) {
    	List<UserInfo> list = userService.findById(userInfo.getId());
    	if(list.size()>0) {
    		UserInfo userInfoOld = list.get(0);
    		String fybm = userInfo.getFybm();
    		fybm = new StringEditor(fybm).trimAll().toString();
    		userInfoOld.setFybm(fybm);
    		if (fybm.substring(1).equals("00")) {
    			userInfoOld.setFytype("高");
    		} else if (fybm.substring(2).equals("0")) {
    			userInfoOld.setFytype("中");
    		} else {
    			userInfoOld.setFytype("辖");
    		}
    		String province = PropertiesUtil.getProperty(fybm.substring(0, 1));
    		userInfoOld.setProvince(province);
    		userInfoOld.setPassword(userInfo.getPassword());
    		userInfoOld.setFymc(userInfo.getFymc());
    		userService.save(userInfoOld);
    		return new Result(200, "修改用户成功", null);
    	}else {
    		return new Result(403, "修改用户失败", null);
    	}

	}
    @RequestMapping(value = "/pageUser", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> query(@RequestParam(value = "limit", required = false, defaultValue = "10") String limit,
			@RequestParam(value = "offset", required = false, defaultValue = "0") String offset,UserInfo userInfo) {
    	Sort sort = new Sort(Direction.DESC,"id");
    	Pageable pageable = PageRequest.of(Integer.valueOf(offset)/Integer.valueOf(limit), Integer.valueOf(limit), sort);
		PageInfo<UserInfo> pageInfo = userService.getPageByUserInfo(userInfo.getName()==null?"":userInfo.getName(), userInfo.getFymc()==null?"":userInfo.getFymc(), userInfo.getProvince()==null?"":userInfo.getProvince(), userInfo.getFytype()==null?"":userInfo.getFytype(), pageable);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("count", pageInfo.getRecords());
		result.put("queryData", pageInfo.getRows());
		return result;
    }

   /* @GetMapping("/findByName")
    public List<UserInfo> findByName(String name) {
        return userRepository.findByName(name);
    }*/


    /*@RequestMapping(value = "/pageUser", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public Map<String,Object> page(HttpServletResponse res,@RequestParam(value = "limit", required = false, defaultValue = "10") String limit,
			@RequestParam(value = "offset", required = false, defaultValue = "0") String offset) throws UnsupportedEncodingException{
		res.setHeader("Access-Control-Allow-Origin", "*");
		Sort sort = new Sort(Direction.DESC,"id");
		Pageable pageable = PageRequest.of(Integer.valueOf(offset)/Integer.valueOf(limit), Integer.valueOf(limit), sort);
		PageInfo<UserInfo> pageInfo = userService.page(pageable);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("count", pageInfo.getRecords());
		result.put("queryData", pageInfo.getRows());
		return result;
	}*/
    
    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(int id){
    	boolean b = userService.delete(id);
    	if(b) {
    		return new Result(200,"删除用户成功",null);
		}else {
			return new Result(404,"删除用户失败",null);
		}
    }
    @PostMapping("/tree")
    @ResponseBody
    public JsonResult<List<FyNodeView>> tree() {
			FyTreeItem root = this.buildFyTree();
    		List<FyNodeView> tree = buildFunctionTree(root);
    		return JsonResult.success(tree);
       
    }
	public FyTreeItem buildFyTree() {
    	List<Fypz> list = tFypzService.queryAll();
        return FyTreeBuildUtil.buildFyTree(list);

    }
	private List<FyNodeView> buildFunctionTree(FyTreeItem node){
  		List<FyTreeItem> list = node.getChildren();
      	if(list.size()==0){
      		return Collections.EMPTY_LIST;
      	}
      	List<FyNodeView> views = new ArrayList<FyNodeView>(list.size());
      	for(FyTreeItem item :list){
      		FyNodeView view = new FyNodeView();
      		view.setCode(item.getData().getCFbdm());
      		view.setName(item.getData().getCMc());
      		view.setId(item.getData().getId());
      		//view.setAccessUrl(item.getData().getAccessUrl());
      		List<FyNodeView> children = this.buildFunctionTree(item);
      		view.setChildren(children);
      		views.add(view);
      	}
      	return views;
     }
	@CrossOrigin
	@RequestMapping(value = "/getIp", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
	public Result getIp(HttpServletRequest request) {
		/*System.out.println(Class.class.getClass().getResource("/").getPath());
		System.out.println(request.getSession().getServletContext().getRealPath("") ); */
		System.out.println(IpUtil.getRemoteIp(request));
		System.out.println(IpUtil.getUserIP(request));
		System.out.println(IpUtil.getIpAddress(request));
		String ip = IpUtil.getUserIP(request);
		List<UserInfo> list = userService.findByIp(ip);
		if(list.size()>0) {
			return new Result(200, "获取IP地址成功", list.get(0));
		}else {
			return new Result(405, "此IP地址还未录入系统，请联系管理员", null);
		}
		
		
	}
}
